import '../../../component/webc';

import { IpcRendererEvent } from 'electron';
import electronUtils from '../../../common/electron';
import { IpcMainEventEnum, IpcRendererEventEnum } from '../../../common/enum';

import WebcDialog from '../../../component/webc/dialog/api';
import { IConfig as ServerConfig, IServer } from '../../../common/serve';

let serverConfig: null | ServerConfig = null;
let addServerDialog: null | WebcDialog = null;
let modServerDialog: null | WebcDialog = null;

let isInit = true;
electronUtils.ipcRenderer.on(IpcRendererEventEnum.RENDERER_ENV, (_, env) => {
    if (isInit && env) {
        isInit = false;
        init();
    }
});

/**
 * 初始化
 */
function init() {
    bindEvent();

    electronUtils.ipcRenderer.on(IpcRendererEventEnum.GET_SERVE_CONFIG, (_: IpcRendererEvent, arg: { serverConfig: ServerConfig }) => {
        serverConfig = arg.serverConfig;
        rendererEleForServerConfig();
    });
    electronUtils.ipcRenderer.send(IpcMainEventEnum.SERVE_RENDERER_READY);
}

/**
 * 绑定事件
 */
function bindEvent() {
    // ...
    window._event = {
        // 查找资源
        findAssets: async () => {
            try {
                const { paths } = await electronUtils.showOpenDialog({ type: 'selectDir' });
                if (paths.length) {
                    const assetsDirInput = window.document.querySelector('.webc-dialog div[slot="content"] .input.assets-dir');
                    if (assetsDirInput) {
                        (assetsDirInput as HTMLInputElement).value = paths[0];
                    }
                }
            } catch (error) {
                console.error(error);
            }
        },

        // 打开添加服务对话框
        openDddServerDialog: () => {
            const webcDialog = new WebcDialog({
                cache: false,
                id: 'add-server-dialog',
                templateId: 'add-server-dialog-slot',
                innerClassName: 'add-server-dialog-wrapper',
            });
            webcDialog.openDialog();
            addServerDialog = webcDialog;
        },
        // 添加服务对话框取消回调
        addServerCancel: () => {
            addServerDialog?.closeDialog();
        },
        // 添加服务对话框确认回调
        addServerConfirm: () => {
            addServer();
            rendererEleForServerConfig();
            addServerDialog?.closeDialog();
        },

        // 打开编辑服务对话框
        openModServerDialog: (serverName: string) => {
            const server = serverConfig?.servers.find(f => f.serverName === serverName);
            if (server) {
                const webcDialog = new WebcDialog({
                    cache: false,
                    id: 'mod-server-dialog',
                    templateId: 'mod-server-dialog-slot',
                    innerClassName: 'mod-server-dialog-wrapper',
                    templateData: { ...server },
                });
                webcDialog.openDialog();
                modServerDialog = webcDialog;
            }
        },
        // 编辑服务对话框取消回调
        modServerCancel: () => {
            modServerDialog?.closeDialog();
        },
        // 编辑服务对话框确认回调
        modServerConfirm: (serverName: string) => {
            toggleServer(serverName, false);
            modServer(serverName);
            rendererEleForServerConfig();
            modServerDialog?.closeDialog();
        },

        // 开启/关闭服务
        toggleServer: (serverName: string) => {
            toggleServer(serverName);
            rendererEleForServerConfig();
        },
        // 编辑服务
        editServer: () => {},
        // 删除服务
        delServer: (serverName: string) => {
            toggleServer(serverName, false);
            delServer(serverName);
            rendererEleForServerConfig();
        },
    };
}

/**
 * 在页面上渲染服务列表
 */
function rendererEleForServerConfig() {
    const templateEle = document.querySelector('#server-item-template');

    if (templateEle) {
        const template = templateEle.innerHTML;

        // 模板参数替换
        let elements = '';
        if (serverConfig) {
            serverConfig.servers.forEach(server => {
                let tmp = template;
                for (const field in server) {
                    const regExp = new RegExp(`{ ${field} }`, 'g');
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    tmp = tmp.replace(regExp, (server as Record<string, any>)[field] || '');
                }
                elements += tmp;
            });

            // 渲染元素
            const targetEle = document.querySelector('.server-list-wrap');
            targetEle && (targetEle.innerHTML = elements);
        }
    }
}

/**
 * 添加服务
 */
function addServer() {
    const port = $('.add-server-form .server-port').val();
    const serverName = $('.add-server-form .server-name').val();
    const assetsDirPath = $('.add-server-form .assets-dir').val();

    if (port && serverName && assetsDirPath) {
        const config: IServer = {
            isRun: false,

            port: Number(port),
            serverName: String(serverName),
            assetsDirPath: String(assetsDirPath),
            defaultAssets: 'index.html',
            rewrite: 'index.html',

            openGZip: false,
            openHttps: false,

            privateKey: '',
            certificate: '',
        };

        serverConfig?.servers.push(config);
        electronUtils.ipcRenderer.send(IpcMainEventEnum.ADD_SERVE_PROCESS, config);
    }
}

/**
 * 编辑服务
 */
function modServer(serverName: string) {
    const port = $('.mod-server-form .server-port').val();
    const assetsDirPath = $('.mod-server-form .assets-dir').val();

    if (port && serverName && assetsDirPath) {
        const config: IServer = {
            isRun: false,

            port: Number(port),
            serverName: String(serverName),
            assetsDirPath: String(assetsDirPath),
            defaultAssets: 'index.html',
            rewrite: 'index.html',

            openGZip: false,
            openHttps: false,

            privateKey: '',
            certificate: '',
        };

        const serverIndex = serverConfig?.servers.findIndex(f => f.serverName === serverName);
        if (serverIndex !== undefined) {
            if (serverConfig?.servers[serverIndex]) {
                serverConfig?.servers.splice(serverIndex, 1, config);
                electronUtils.ipcRenderer.send(IpcMainEventEnum.MOD_SERVE_PROCESS, config);
            }
        }
    }
}

/**
 * 开启/关闭服务
 */
function toggleServer(serverName: string, flag?: boolean) {
    // ...
    const serverIndex = serverConfig?.servers.findIndex(f => f.serverName === serverName);

    if (serverIndex !== undefined) {
        if (serverConfig?.servers[serverIndex]) {
            // ...
            const current = serverConfig.servers[serverIndex];

            if (flag === true) {
                current.isRun = true;
                electronUtils.ipcRenderer.send(IpcMainEventEnum.RUN_SERVE_PROCESS, current);
                return;
            } else if (flag === false) {
                current.isRun = false;
                electronUtils.ipcRenderer.send(IpcMainEventEnum.CLS_SERVE_PROCESS, current);
                return;
            }

            const isRun = current.isRun;
            current.isRun = !isRun;
            if (isRun) {
                electronUtils.ipcRenderer.send(IpcMainEventEnum.CLS_SERVE_PROCESS, current);
            } else {
                electronUtils.ipcRenderer.send(IpcMainEventEnum.RUN_SERVE_PROCESS, current);
            }
        }
    }
}

/**
 * 删除服务
 */
function delServer(serverName: string) {
    const serverIndex = serverConfig?.servers.findIndex(f => f.serverName === serverName);
    if (serverIndex !== undefined) {
        if (serverConfig?.servers[serverIndex]) {
            electronUtils.ipcRenderer.send(IpcMainEventEnum.DEL_SERVE_PROCESS, serverConfig.servers[serverIndex]);
            serverConfig.servers.splice(serverIndex, 1);
        }
    }
}
